package org.langqiao.io;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JToolBar;

/**
 * 按下鼠标开始，获得拖动鼠标的当前点的坐标，在两点之间画一条直线，这样就画出了鼠标拖动的轨迹
 * @author YMY
 */
public class PaintJPGJFrame extends JFrame implements ActionListener {
	
	private String filename;//JPG图象名
	private PaintCanvas canvas;//自定义画布组件
	
	//构造方法
	public PaintJPGJFrame(String filename) {
		
		super("画图并保存JPG图象文件");
		this.setBounds(400,300,400,300);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		JToolBar toolbar = new JToolBar();
		this.getContentPane().add(toolbar,"North");
		JButton button = new JButton(new ImageIcon("save.gif"));//保存按钮
        button.addActionListener(this); 
		toolbar.add(button);
		canvas = new PaintCanvas();//创建自定义的画布组件
		this.getContentPane().add(canvas);
		this.setVisible(true);
		this.filename = filename;
	}
	
	//内部类
	class PaintCanvas extends Canvas implements MouseMotionListener,MouseListener {
		Point start,end;//定义两个点，始点和终点
		BufferedImage image;
		Graphics g_image;
		//内部类的构造方法
		public PaintCanvas() {
			image = new BufferedImage(400,300,BufferedImage.TYPE_INT_RGB);
			g_image = image.getGraphics();
			g_image.setColor(Color.red);
			start=end=null;
			this.addMouseMotionListener(this);
			this.addMouseListener(this);
		}
		//实现MouseMotionListener接口
		public void mouseMoved(MouseEvent me){}
		public void mouseDragged(MouseEvent me){
			start=end;
			end=new Point(me.getX(),me.getY());
			g_image.drawLine(start.x,start.y,end.x,end.y);//画直线
			repaint();
		}
		
		//实现MouseListener接口
		public void mousePressed(MouseEvent me){
			end=new Point(me.getX(),me.getY());
		}
		
		public void mouseReleased(MouseEvent me){};//鼠标释放
		public void mouseClicked(MouseEvent me){};//鼠标单击
		public void mouseEntered(MouseEvent me){};//鼠标进入
		public void mouseExited(MouseEvent me){};//鼠标离开时
	    //备注：问题：这里的鼠标离开时所要复写的方法一定要注意写正确mouseExited
		
		public void paint(Graphics g){
			g.drawImage(image,0,0,this.getWidth(),this.getHeight(),this);
		}
		//消除抖动
		public void update(Graphics g){
			paint(g);
		}
	}
	
	//单击按钮事件 的处理方法
	public void actionPerformed(ActionEvent e) {
		//将canvas中的图像保存在名为filename的JPG文件中
		try{
			//JPEGCodec.createJPEGEncoder(new FileOutputStream(filename)).encode(canvas.image);
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public static void main(String[] args){
		new PaintJPGJFrame("paint.jpg");
	}
}
